/*
 * Copyright 2009 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.randis.dailyplanner.dao;

import java.util.List;
import java.util.UUID;

import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;
import javax.jdo.Transaction;

import com.randis.dailyplanner.ServiceLocator;
import com.randis.dailyplanner.domain.Activity;
import com.randis.dailyplanner.domain.User;

/**
 *
 * @author Alexei Petinov
 */
public class ActivitiesDao {

	private static final PersistenceManagerFactory pmfInstance = ServiceLocator.getInstance().getPMFInstance();
	
    public Activity getActivity(String id) {
    	PersistenceManager pm = pmfInstance.getPersistenceManager();
    	Activity activity = null;
    	try {
    		activity = pm.getObjectById(Activity.class, id);
        	pm.detachCopy(activity); 
    	} finally {
            pm.close(); 
    	}

    	return activity;
    }

    public Activity saveActivity(Activity activity, User user) {
    	PersistenceManager pm = pmfInstance.getPersistenceManager();
    	Transaction tx = pm.currentTransaction();
    	
    	try {
    		tx.begin();
    		if (activity.getId() == null) {
    			activity.setId("a" + UUID.randomUUID().toString());
    		}
    		activity.setUserId(user.getId());
    		activity = pmfInstance.getPersistenceManager().makePersistent(activity);
    		tx.commit();
    	} finally {
    		if (tx.isActive()) {
                tx.rollback();
            }
        	pm.close();
    	}
    	return activity;
    }

	public List<Activity> list() {
    	String queryString = "select from " + Activity.class.getName();
		return doListActivities(queryString);
    }

    public void deleteActivity(String id) {
    	PersistenceManager pm = pmfInstance.getPersistenceManager();
    	Transaction tx = pm.currentTransaction();
    	
    	try {
    		tx.begin();
    		Activity activity = pm.getObjectById(Activity.class, id);
    		pm.deletePersistent(activity);
    		tx.commit();
    	} finally {
    		if (tx.isActive()) {
                tx.rollback();
            }
        	pm.close();
    	}
    }

	public List<Activity> listNonProcessedActivities() {
    	String queryString = "select from " + Activity.class.getName() + " where processed==false";
    	return doListActivities(queryString);
	}

	private List<Activity> doListActivities(String queryString) {
    	PersistenceManager pm = pmfInstance.getPersistenceManager();
    	Query query = pm.newQuery(queryString);
    	
    	List<Activity> activities = null;
    	
        try {
        	activities = (List<Activity>) query.execute();
        	pm.detachCopyAll(activities); 
        } finally {
        	query.closeAll();
            pm.close(); 
        }
        
		return activities;
	}
}
